const config = require('../../config/index')
const { login,wxRequest } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    loading: false,
    baseUrl: config.baseUrl,
    theme: wx.getStorageSync('InvoiceLoanTheme') || ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    // 528d84861627e1147fcbbf90ffab6b0e
    const token = wx.getStorageSync('InvoiceLoanToken')
    if(!token){
      login(()=>{
        that.fetchData.bind(that)
        that.queryTheme,bind(that)
      })
    } else {
      that.fetchData()
      that.queryTheme()
    }
  },
  fetchData(){
    const that = this
    that.setData({
      loading: true
    })
    wxRequest({
      url: `${config.baseUrl}/product/list`,
      method:'GET',
      success(res){
        that.setData({
          list: res.data.data || []
        })
      },
      invalidCb(){
        that.fetchData()
      },
      complete(){
        that.setData({
          loading: false
        })
      }
    })
  },
  queryTheme(){
    const that = this
    wxRequest({
      url: `${that.data.baseUrl}/theme`,
      invalidCb(){
        that.queryTheme()
      },
      success(res){
        const theme = res.data.data
        that.setData({
          theme
        })
        wx.setStorageSync('InvoiceLoanTheme', theme)
      }
    })
  },
  handleToApplication() {
    wx.navigateTo({
      url: '/pages/applicationList/index',
    })
  },
  handleToDetail(e){
    const {rateFlor,amtCeiling,amtFlor,prodName,prdCode,productType} = e.currentTarget.dataset
    const invoiceLoanProductType = wx.getStorageSync('InvoiceLoanProductType')
    if(invoiceLoanProductType !== productType) {
      wx.setStorage({
        key: 'InvoiceLoanFormData',
        data: JSON.stringify({
          businessLicensePath:'',
          creditPath:'',
          formData: {},
          liveAddr: []
        })
      })
    }
    wx.setStorage({
      key: 'InvoiceLoanAmt',
      data: JSON.stringify({
        max: amtCeiling,
        min: amtFlor
      })
    })
    wx.setStorage({
      key:'InvoiceLoanPrdCode',
      data:prdCode
    })
    wx.setStorage({
      key: 'InvoiceLoanProductType',
      data: productType
    })
    
    wx.navigateTo({
      url: `/pages/productDetail/index?type=${productType}&prodName=${prodName}&rateFlor=${rateFlor}&amtCeiling=${amtCeiling}`,
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if(this.data.loading) return
    this.fetchData()
    wx.stopPullDownRefresh()
  },
})